package fileUtils

import (
	"bufio"
	"bytes"
	"image"
	"image/color"
	"image/draw"
	"image/jpeg"
	"io"
	"os"
)

func ReadFile(url string) ([]byte, bool) {
	fp, err := os.OpenFile(url, os.O_CREATE|os.O_APPEND, 6) // 读写方式打开
	if err != nil {
		// 如果有错误返回错误内容
		return nil, false
	}
	defer fp.Close()
	bytes, err := io.ReadAll(fp)
	if err != nil {
		panic(err)
		return nil, false
	}
	return bytes, true
}
func WriteFile(data []byte, toPath string) bool {
	file, err := os.OpenFile(toPath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		panic(err)
		return false

	}
	write := bufio.NewWriter(file)
	write.Write(data)
	return true

}

func ComImgJpeg(data []byte) []byte {
	imgSrc, _, err := image.Decode(bytes.NewReader(data))
	if err != nil {
		return data
	}
	newImg := image.NewRGBA(imgSrc.Bounds())
	draw.Draw(newImg, newImg.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
	draw.Draw(newImg, newImg.Bounds(), imgSrc, imgSrc.Bounds().Min, draw.Over)
	buf := bytes.Buffer{}
	err = jpeg.Encode(&buf, newImg, &jpeg.Options{Quality: 1})
	//err = png.Encode(&buf, newImg)
	if err != nil {
		return data
	}
	if buf.Len() > len(data) {
		return data
	}
	return buf.Bytes()
}
